package com.example.demo.controller;

import com.example.demo.model.UserEntity;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

@Controller
public class HelloController {
    private static final Logger log = LoggerFactory.getLogger(HelloController.class);

    @Value("app.param")
    String appParam;

    @Autowired
    StringRedisTemplate stringRedisTemplate;


    @GetMapping("/hi")
    @ResponseBody
    public String hi(String name) {
        int rnd = new Random().nextInt(1000);

        System.out.println(rnd);

        log.info("请求访问 ：" + name + "  rnd:" + rnd);

        return "hi! [" + name + "] runEnv: " + appParam + "rnd:" + rnd;
    }

    @GetMapping("/redis")
    @ResponseBody
    public String redis() {
        int rnd = new Random().nextInt(1000);
        //字符串
        stringRedisTemplate.opsForValue().set("rediskey", "redis value " + rnd);

        String redisvalue = stringRedisTemplate.opsForValue().get("rediskey");

        log.info("rediskey：" + redisvalue);

        return redisvalue;
    }

    @RequestMapping("/list")
    public String listUser(Model model) {
        List<UserEntity> userList = new ArrayList<UserEntity>();
        for (int i = 0; i < 10; i++) {
            userList.add(new UserEntity("张三" + i, "Pwd-" + i));
        }
        model.addAttribute("users", userList);
        return "user/list";
    }
}
